import { defineStore } from 'pinia'
import { addToCartApi } from '@/api/cart'
import useUserStore from './user'



//购物车管理的仓库
  const useCartStore=defineStore('cart',{
    state(){//状态数组
        return{
            cart:[] as CartProduct[],
        }

    },
    getters:{//store中的计算属性
        //是否全选
        allChecked(state){
            return state.cart.every(curr=>curr.checked)
        },
        //所有选中商品的合计金额
        totalMoney(state){
            return state.cart.reduce((sum,curr)=>{
                if(curr.checked){
                   sum+=curr.price*(curr.amount as number)
                 // sum=sum +curr.price*curr.amount
                }
                return sum
            },0)*100

        },
        //购物车总商品数量
        totalAmount(state){
            return state.cart.reduce((sum,curr)=>{
                return sum+(curr.amount as number)
            },0)

        }

    },
    actions:{//更新状态数据的方法
        async addToCart(prod:any){
         const store=useUserStore()
          const result=await addToCartApi(store.token,prod)
          console.log('加入购物车结果ddd',result)
         const has=this.cart.find(curr=>curr.id===prod.id)
         console.log('has数据',has)
         if(has){//有则叠加数量
            has.amount=(has.amount??1)+(prod.amount??1)
            console.log(has.amount)
         }else{//没有则将当前选购商品保存到cart数组中
            this.cart.push({
                ...prod,
                amount:1,
                checked:true
            })

         }
       
         // return result
            
        }

    },
    persist: true, 
  
})
export default useCartStore